package com.zz.framework.widget;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zz.framework.R;
import com.zz.framework.core.utils.LogUtils;
import com.zz.framework.core.utils.ZCountDownTimer;

import java.io.File;

import androidx.appcompat.widget.AppCompatButton;


/**
 * @version: V1.0
 * 带录音功能的button
 */
public class RecordButton2 extends AppCompatButton {
    public RecordButton2(Context context) {
        super(context);
        init();
    }

    public RecordButton2(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public RecordButton2(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public String getLocalFolderPath() {
        String  rootDir = Environment.getExternalStorageDirectory().getPath() + "/" + Environment.DIRECTORY_DOWNLOADS;
        File file = new File(rootDir, "hhCache/recordVoice");
        if (!file.exists()){
            file.mkdirs();
        }
        return file.getAbsolutePath();
    }

    private String mFile = getLocalFolderPath() + "/" + "voice_" + System.currentTimeMillis() + ".mp3";

    private void updateFilePath() {
        mFile = getLocalFolderPath() + "/" + "voice_" + System.currentTimeMillis() + ".mp3";
    }

    private OnFinishedRecordListener finishedListener;
    /**
     * 最短录音时间
     **/
    private int MIN_INTERVAL_TIME = 1000;
    /**
     * 最长录音时间
     **/
    private int MAX_INTERVAL_TIME = 1000 * 61;


    private static View view;

    private TextView mStateTV;

    private ImageView mStateIV;

    private MediaRecorder mRecorder;
    private ObtainDecibelThread mThread;
    private Handler volumeHandler;
    private float y;

    public void setOnFinishedRecordListener(OnFinishedRecordListener listener) {
        finishedListener = listener;
    }
    private static long startTime;
    private Dialog recordDialog;
    private static int[] res = {R.drawable.ic_volume_0, R.drawable.ic_volume_1, R.drawable.ic_volume_2, R.drawable.ic_volume_3, R.drawable.ic_volume_4, R.drawable.ic_volume_5, R.drawable.ic_volume_6, R.drawable.ic_volume_7, R.drawable.ic_volume_8};

    @SuppressLint("HandlerLeak")
    private void init() {
        volumeHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == -100) {
                    stopRecording();
                    recordDialog.dismiss();
                } else if (msg.what != -1) {
                    mStateIV.setImageResource(res[msg.what]);
                }
            }
        };
    }

    private AnimationDrawable anim;
    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        y = event.getY();
        if (mStateTV != null && mStateIV != null && y < 0) {
            mStateTV.setText("取消");
            mStateIV.setImageDrawable(getResources().getDrawable(R.drawable.ic_volume_cancel));
        } else if (mStateTV != null) {
            mStateTV.setText("取消");
        }
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                setText("松开发送");
                initDialogAndStartRecord();
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                this.setText("开始说话");
                if (y >= 0) {
                    if ((System.currentTimeMillis() - startTime <= MAX_INTERVAL_TIME)) {
                        LogUtils.error("结束录音:");
                        finishRecord();
                    }
                } else if (y < 0) {  //当手指向上滑，会cancel
                    cancelRecord();
                }
                break;
        }

        return true;
    }

    /**
     * 初始化录音对话框 并 开始录音
     */
    private void initDialogAndStartRecord() {
        startTime = System.currentTimeMillis();
        recordDialog = new Dialog(getContext(), R.style.like_toast_dialog_style);
        recordDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 设置对话框背景为透明
        if (recordDialog.getWindow() != null) {
            recordDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        }
        view = View.inflate(getContext(), R.layout.dialog_record, null);
        mStateIV = (ImageView) view.findViewById(R.id.rc_audio_state_image);
        mStateTV = (TextView) view.findViewById(R.id.rc_audio_state_text);
        mStateIV.setImageDrawable(getResources().getDrawable(R.drawable.anim_mic));
        anim = (AnimationDrawable) mStateIV.getDrawable();
        anim.start();
        mStateIV.setVisibility(View.VISIBLE);
        mStateTV.setVisibility(View.VISIBLE);
        mStateTV.setText("手指上滑,取消发送");
        recordDialog.setContentView(view, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        recordDialog.setOnDismissListener(onDismiss);
        WindowManager.LayoutParams lp = recordDialog.getWindow().getAttributes();
        lp.gravity = Gravity.CENTER;
        startRecording();
        recordDialog.show();
    }

    /**
     * 放开手指，结束录音处理
     */
    private void finishRecord() {
        long intervalTime = System.currentTimeMillis() - startTime;
        if (intervalTime < MIN_INTERVAL_TIME) {
            LogUtils.error("录音时间太短");
            volumeHandler.sendEmptyMessageDelayed(-100, 500);
            mStateIV.setImageDrawable(getResources().getDrawable(R.drawable.ic_volume_wraning));
            mStateTV.setText("时间太短");
            anim.stop();
            File file = new File(mFile);
            file.delete();
            return;
        } else {
            stopRecording();
            recordDialog.dismiss();
        }
        LogUtils.error("录音完成的路径:" + mFile);
        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(mFile);
            mediaPlayer.prepare();
            mediaPlayer.getDuration();
            LogUtils.error("获取到的时长:" + mediaPlayer.getDuration() / 1000);
        } catch (Exception e) {

        }
        if (finishedListener != null) {
            finishedListener.onFinishedRecord(mFile, mediaPlayer.getDuration());
        }
    }

    /**
     * 取消录音对话框和停止录音
     */
    public void cancelRecord() {
        stopRecording();
        recordDialog.dismiss();
        File file = new File(mFile);
        file.delete();
    }


    //5分钟
    ZCountDownTimer timer = new ZCountDownTimer(MAX_INTERVAL_TIME+10,1000) {
        @Override
        public void onFinish() {
            finishRecord();
        }

        @Override
        public void onTick(long millisUntilFinished) {

        }
    };

    /**
     * 执行录音操作
     */
    private void startRecording() {
        updateFilePath();
        timer.restart();
        if (mRecorder != null) {
            mRecorder.reset();
        } else {
            mRecorder = new MediaRecorder();
        }
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        File file = new File(mFile);
        LogUtils.error("创建文件的路径:" + mFile);
        LogUtils.error("文件创建成功:" + file.exists());
        mRecorder.setOutputFile(mFile);
        try {
            mRecorder.prepare();
            mRecorder.start();
        } catch (Exception e) {
            LogUtils.error("preparestart异常,重新开始录音:" + e.toString());
            e.printStackTrace();
            mRecorder.release();
            mRecorder = null;
            startRecording();
        }
    }


    private void stopRecording() {
        if (mThread != null) {
            mThread.exit();
            mThread = null;
        }
        timer.cancel();
        if (mRecorder != null) {
            try {
                mRecorder.stop();//停止时没有prepare，就会报stop failed
                mRecorder.reset();
                mRecorder.release();
                mRecorder = null;
            } catch (RuntimeException pE) {
                pE.printStackTrace();
            } finally {
                if (recordDialog.isShowing()) {
                    recordDialog.dismiss();
                }
            }
        }

    }

    private class ObtainDecibelThread extends Thread {
        private volatile boolean running = true;
        public void exit() {
            running = false;
        }
        @Override
        public void run() {
            LogUtils.error("检测到的分贝001:");
            while (running) {
                if (mRecorder == null || !running) {
                    break;
                }
                // int x = recorder.getMaxAmplitude(); //振幅
                int db = mRecorder.getMaxAmplitude() / 600;
                LogUtils.error("检测到的分贝002:" + mRecorder);
                if (db != 0 && y >= 0) {
                    int f = (int) (db / 5);
                    if (f == 0) {
                        volumeHandler.sendEmptyMessage(0);
                    } else if (f == 1) {
                        volumeHandler.sendEmptyMessage(1);
                    } else if (f == 2) {
                        volumeHandler.sendEmptyMessage(2);
                    } else if (f == 3) {
                        volumeHandler.sendEmptyMessage(3);
                    } else if (f == 4) {
                        volumeHandler.sendEmptyMessage(4);
                    } else if (f == 5) {
                        volumeHandler.sendEmptyMessage(5);
                    } else if (f == 6) {
                        volumeHandler.sendEmptyMessage(6);
                    } else {
                        volumeHandler.sendEmptyMessage(7);
                    }
                }
                volumeHandler.sendEmptyMessage(-1);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private DialogInterface.OnDismissListener onDismiss = new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialog) {
            stopRecording();
        }
    };

    public interface OnFinishedRecordListener {
        /**
         *
         * @param audioPath
         * @param time 毫秒
         */
        void onFinishedRecord(String audioPath, int time);
    }


}
